﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.Mvc;
using BLL.ComplexClasses;
using BLL;
using System.IO;
using System.Configuration;
namespace ithub.Controllers
{
    public class ImagesController : Controller
    {
        //
        // GET: /Images/

        public ActionResult Index(long id ,string module)
        {

            return View();
        }

        [HttpPost]
        public JsonResult SaveRecord(Image objImage)
        {

            if (Request.Files != null)
            {
                foreach (string uploadedFileName in Request.Files)
                {
                    HttpPostedFileBase file = Request.Files[uploadedFileName];
                    if (file != null && file.ContentLength > 0)
                    {
                        objImage.path = Guid.NewGuid() + Path.GetExtension(file.FileName);

                        //set the bynary data to save into database
                        var data = new byte[file.ContentLength];
                        file.InputStream.Read(data, 0, file.ContentLength);


                        //check if directory not exists
                        if (!Directory.Exists(Server.MapPath(
                            ConfigurationManager.AppSettings[App_Utils.clsConstants.Uploads]
                            )))
                        {
                            Directory.CreateDirectory(Server.MapPath(
                            ConfigurationManager.AppSettings[App_Utils.clsConstants.Uploads]
                            ));
                        }

                        string imagePath = Path.Combine(Server.MapPath(
                            ConfigurationManager.AppSettings[App_Utils.clsConstants.Uploads]
                            ), (objImage.path));
                        file.SaveAs(imagePath);

                        BL_Images.SaveRecord(objImage);
                        //TODO
                    }
                } //end of foreach

                return Json(new { Result = App_Utils.clsConstants.OK });

            } //end of Request.Files != null
            else
            {
                return Json(new { Result = App_Utils.clsConstants.ERROR });
            }
        }

    }
}
